package beanutils;


import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;

import introspector.Student;

/**
 * beanutils方式操作bean
 * @author xiayaqiong
 *
 */
public class Demo {

/*public static void main(String[] args) throws Exception {
	String name="xiayaq";
	String password="123";
	String age="12";
	String birthday="1998-09-09";
	Student student=new Student();
	BeanUtils.setProperty(student, "name", name);
	BeanUtils.setProperty(student, "password", password);
	BeanUtils.setProperty(student, "age", age);//beanutis会自动转换数据类型,基本类型，复杂类型除外
	//如果出现复杂类型，注册一个转换器
	BeanUtils.setProperty(student, "birthday", birthday);
	ConvertUtils.register(new DateLocaleConverter(), Date.class);
	System.out.println(student.getBirthday());

}*/
	
	public static void main(String[] args) throws Exception {
		String name="xiayaq";
		String password="123";
		String age="12";
		String birthday="1998-09-09";
		Student student=new Student();
		BeanUtils.setProperty(student, "name", name);
		BeanUtils.setProperty(student, "password", password);
		BeanUtils.setProperty(student, "age", age);//beanutis会自动转换数据类型,基本类型，复杂类型除外
		//如果出现复杂类型，注册一个转换器

		ConvertUtils.register(new Converter() {
			
			@Override
			public Object  convert(Class type, Object value) {
				if (value==null) {
					return null;
				}
				SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd");
			Date date = null;
			try {
				date = (Date) format.parse((String) value);
			
			} catch (ParseException e) {
			
			throw new ConversionException(e);
			}
			return date;
		
			}
		}, Date.class);
		BeanUtils.setProperty(student, "birthday", birthday);
		System.out.println(student.getBirthday());
	}
	
}
